﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using ECare.BUS;
using ECare.BUS.Data;
using ECare.BUS.Workers;
using ECare.Client.templates;

namespace ECare.Client.frms
{
    public partial class frmOutInfoNew : frmInfo
    {
        public frmOutInfoNew()
        {
            InitializeComponent();

            this.Load += frmOutInfoNew_Load;

        }

        void frmOutInfoNew_Load(object sender, EventArgs e)
        {
            //throw new NotImplementedException();
            this.cbResources.DataSource = ResourcesHelper.GetAllResources();
            this.cbResources.DisplayMember = "ResourceName";
            this.cbResources.ValueMember = "ResourceId";

            //
            this.cbUsers.DataSource = UserInfoHelper.GetUsers();
            this.cbUsers.DisplayMember = "UserName";
            this.cbUsers.ValueMember = "UserId";

            this.LoadInformation();
        }


        private void LoadInformation()
        {
            if (this.entity != null)
            {
                var currentoutinfo = this.entity as ResourceOutInfo;
                this.txtSheetNo.Text = currentoutinfo.resource_out_sheet_no;
                this.cbResources.SelectedValue = currentoutinfo.resource_id;
                this.txtNumbers.Value = currentoutinfo.resource_numbers.HasValue?currentoutinfo.resource_numbers.Value:0;
                this.cbUsers.SelectedValue = currentoutinfo.resource_get_by;
                this.txtGetDate.Value = currentoutinfo.resource_get_time.HasValue
                    ? currentoutinfo.resource_get_time.Value
                    : DateTime.Now;

            }
        }





        public event EntitySavedHandler Saved;

        private void btnSave_Click(object sender, EventArgs e)
        {
            #region Validate
            if (!this.ValidateTextControl(this.txtSheetNo))
                return;

            if (!this.ValidateDropdownlist(this.cbResources))
                return;

            if (!this.ValidateDropdownlist(this.cbUsers))
                return;

            if (this.txtNumbers.Value == 0)
            {
                this.errorProvider1.SetError(this.txtNumbers, "?");
                return;
            }
            else
            {
                this.errorProvider1.SetError(this.txtNumbers, string.Empty);
            }
            #endregion


            if (this.entity == null)
            {
                var newout = new ResourceOutInfo();

                newout.resource_out_sheet_no = this.txtSheetNo.Text;
                newout.resource_id = int.Parse(this.cbResources.SelectedValue.ToString());
                newout.resource_numbers = (int) this.txtNumbers.Value;
                newout.resource_get_by = (int) this.cbUsers.SelectedValue;
                newout.resource_get_time = this.txtGetDate.Value;
                newout.resource_create_by = ApplicationData.CurrentUserInfo.UserId;
                newout.resource_create_time = DateTime.Now;
                newout.resource_status = CheckStatus.Pending; // 等待出库
                newout.resource_remark = this.txtRemark.Text;

                ResourceOutHelper.CreateResourceOutInfo(newout);
                this.entity = newout;
            }
            else
            {
                var currentoutinfo = this.entity as ResourceOutInfo;

                currentoutinfo.resource_out_sheet_no = this.txtSheetNo.Text;
                currentoutinfo.resource_id = (int)this.cbResources.SelectedValue;
                currentoutinfo.resource_numbers = (int)this.txtNumbers.Value;

                currentoutinfo.resource_get_by = (int)this.cbUsers.SelectedValue;
                currentoutinfo.resource_get_time = this.txtGetDate.Value;
                currentoutinfo.resource_remark = this.txtRemark.Text;

                ResourceOutHelper.UpdateResourceOutInfo(currentoutinfo);

            }

            if (this.Saved != null)
            {
                this.Saved(this.entity);
            }


            if(MessageBox.Show("立即出库？","信息提示",MessageBoxButtons.YesNo, MessageBoxIcon.Information)== DialogResult.No)
                this.Close();//close the curent UI.


            //计算准备出库

            var worker = new ComputeOutFrmHelper();
            worker.id = (this.entity as ResourceOutInfo).resource_out_id;
            worker.RunWorkerCompleted += worker_RunWorkerCompleted;
            worker.RunWorkerAsync();
            frmloading = new frmLoading();
            frmloading.ShowDialog();



           // this.Close();
        }


        private ComputeResult result = null;
        void worker_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
        {
            frmloading.Close();


            //   resource_Id


            result = e.Result as ComputeResult;
            resource_Id.DataSource = ResourcesHelper.GetAllResources();
            resource_Id.DisplayMember = "ResourceName";
            resource_Id.ValueMember = "ResourceId";

            this.grd.DataSource = (e.Result as ComputeResult).result_shown;


            if (result.IsShowReCheckButton)
            {
                this.btnCheck.Visible = true;
            }

            foreach (var msg in (e.Result as ComputeResult).messages)
            {
                if (string.IsNullOrEmpty(this.lblMessages.Text))
                    this.lblMessages.Text = msg;
                else
                {
                    this.lblMessages.Text = this.lblMessages.Text + "\t\n" + msg;
                }
            }

            //show the 重新检验的按钮。
            if ((e.Result as ComputeResult).messages.Count == 0)
            {
                this.btnSave.Visible = false;
                this.btnOut.Visible = true;
            }
          }



        private void btnCheck_Click(object sender, EventArgs e)
        {
            if (MessageBox.Show("这将把过期的物料重新质检?", "信息提示", MessageBoxButtons.YesNo, MessageBoxIcon.Information) ==
             DialogResult.No)
                return;


            //将过期的物料设置为expired.
            var worker = new CommonBackgroundWorker();
            worker.m_delegateFunction = new DelegateFunction(
                () => UpdateExceptionData());
            worker.RunWorkerCompleted += setworker_RunWorkerCompleted;
            worker.RunWorkerAsync();

            frmloading.ShowDialog();
        }
        private void setworker_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
        {
            //   throw new NotImplementedException();
            //
            frmloading.Close();
            if (MessageBox.Show("重新加载出库数据?", "信息提示", MessageBoxButtons.YesNo, MessageBoxIcon.Information) ==
                DialogResult.No)
                return;
            //重新load 

            var worker = new ComputeOutFrmHelper();
            worker.id = (this.entity as ResourceOutInfo).resource_out_id;
            worker.RunWorkerCompleted += worker_RunWorkerCompleted;
            worker.RunWorkerAsync();
            frmloading = new frmLoading();
            frmloading.ShowDialog();

        }

        private object UpdateExceptionData()
        {
            foreach (DataRow data in result.result_shown.Rows)
            {
                if (data["supply_invalidate"] == null)
                {
                    continue;
                }
                var invalidate = DateTime.Parse(data["supply_invalidate"].ToString());
                if (invalidate < DateTime.Now)
                {
                    int supplyID = int.Parse(data["supply_id"].ToString());
                    SupplyInfoHelper.SetExpireStorageStatus(supplyID);
                }
            }
            return null;
        }


        private void btnOut_Click(object sender, EventArgs e)
        {
            if (MessageBox.Show("确认计算出库批次？", "信息提示", MessageBoxButtons.YesNo, MessageBoxIcon.Information) ==
     DialogResult.No)
                return;
            var currentoutinfo = this.entity as ResourceOutInfo;
            currentoutinfo.resource_status = CheckStatus.Checked;
            //ResourceOutHelper.UpdateResourceOutInfo(currentoutinfo);
            if (result == null)
                return;

            if (result.messages.Count > 0)
            {
                MessageBox.Show("存在异常，不能出库.", "信息提示");
                return;
            }

      //      if (MessageBox.Show("确定出库?", "信息提示", MessageBoxButtons.YesNo, MessageBoxIcon.Information) == DialogResult.No)
      //          return;

 

            var dt = result.result;
            var detailIds = new List<int>();
            foreach (DataRow dr in dt.Rows)
            {
                var detail_id = int.Parse(dr["supply_detail_Id"].ToString());
                detailIds.Add(detail_id);
            }

            var createresult = PlanHelper.CreateStorageOutData(currentoutinfo, detailIds);

            if (createresult == true)
            {
                //currentout.plan_isout = true;
                this.Close();
            }
        }
    }
}
